<template>
  <div>
    <el-tabs v-model="activeStep">
      <el-tab-pane label="基本信息" :name="0" />
      <el-tab-pane label="商品详情" :name="1" />
      <el-tab-pane label="其他信息" :name="2" />
    </el-tabs>

    <el-form ref="formRef" :model="localForm" label-width="120px" class="mt-4">
      <div v-show="activeStep === 0">
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="商品名称"
              prop="name"
              :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]"
            >
              <el-input v-model="localForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="库存"
              prop="stock"
              :rules="[{ required: true, message: '请输入库存', trigger: 'blur' }]"
            >
              <el-input-number v-model="localForm.stock" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销量" prop="sales">
              <el-input-number v-model="localForm.sales" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="localForm.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="商品分类"
              prop="category_id"
              :rules="[{ required: true, message: '请选择商品分类', trigger: 'change' }]"
            >
              <el-tree-select
                v-model="localForm.category_id"
                :data="cateTree"
                :props="{ label: 'label', value: 'id' }"
                check-strictly
                clearable
                placeholder="请选择商品分类"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="localForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        <el-form-item
          label="原价"
          prop="price"
          :rules="[{ required: true, message: '请输入价格', trigger: 'blur' }]"
        >
          <el-input-number v-model="localForm.price" :min="0" />
        </el-form-item>
        <el-form-item label="优惠价" prop="salePrice">
          <el-input-number v-model="localForm.salePrice" :min="0" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="localForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="商品标签" prop="tags">
          <el-select
            v-model="localForm.tags"
            multiple
            filterable
            :allow-create="false"
            default-first-option
            placeholder="请选择或输入商品标签"
            class="w-full"
          >
            <el-option v-for="tag in tagList" :key="tag.id" :label="tag.name" :value="tag.name">
              <div style="display: flex; gap: 8px; align-items: center">
                <div
                  :style="{
                    width: '12px',
                    height: '12px',
                    borderRadius: '50%',
                    backgroundColor: tag.color || '#409eff'
                  }"
                />
                <span>{{ tag.name }}</span>
                <span style="font-size: 12px; color: #8492a6">(权重: {{ tag.weight }})</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="localForm.description" type="textarea" />
        </el-form-item>
      </div>

      <div v-show="activeStep === 1">
        <GoodsDetail v-model="localForm" />
      </div>

      <div v-show="activeStep === 2">
        <p>提交</p>
      </div>
    </el-form>

    <div class="flex justify-end mt-4">
      <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
      <el-button v-if="activeStep < 2" type="primary" @click="nextStep">下一步</el-button>
      <el-button v-if="activeStep === 2" type="primary" @click="handleSubmitInternal">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import GoodsDetail from "./GoodsDetail.vue";
import { getCateTree } from "@/api/good-cate";
import { getTags } from "@/api/tag-management";
import { ElMessage } from "element-plus";
import { GoodsForm } from "@/views/mall/goods/utils/rule";

/* ---------- 1. props 只读 ---------- */
const props = defineProps<{
  formInline: GoodsForm | Record<string, any>;
}>();
/* ---------- 2. 内部可写副本，改名 ---------- */
const localForm = ref<GoodsForm | null>(null);

watch(
  () => props.formInline,
  val => {
    localForm.value = JSON.parse(JSON.stringify(val));
  },
  { immediate: true, deep: true }
);

/* ---------- 3. 其余逻辑完全不变，只是变量名换成 localForm ---------- */
const formRef = ref();
const activeStep = ref(0);
const cateTree = ref<any[]>([]);
const tagList = ref<any[]>([]);

const fetchCateTree = async () => {
  // 如果已有数据，避免重复请求
  if (cateTree.value.length > 0) return;

  const { code, data, message } = await getCateTree();
  if (code !== 200) {
    ElMessage.error(message);
    return;
  }
  cateTree.value = data;
};

const fetchTagList = async () => {
  // 如果已有数据，避免重复请求
  if (tagList.value.length > 0) return;

  try {
    const { code, data, message } = await getTags({
      type: 1, // 商品标签类型
      status: 1 // 只获取启用的标签
    });
    if (code === 200) {
      tagList.value = data?.list || [];
    } else {
      ElMessage.error(message || "获取标签列表失败");
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
  }
};

onMounted(() => {
  fetchCateTree();
  fetchTagList();
});

const nextStep = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (activeStep.value < 2) activeStep.value++;
    } else {
      ElMessage.error("请填写完整当前步骤的必填项");
    }
  });
};

const prevStep = () => {
  if (activeStep.value > 0) activeStep.value--;
};

const emit = defineEmits<{
  submit: [form: GoodsForm | null];
}>();

const handleSubmitInternal = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      emit("submit", localForm.value);
    } else {
      ElMessage.error("请填写完整表单");
    }
  });
};

const getFormData = () => localForm.value;

defineExpose({ getFormData, formRef, activeStep, handleSubmitInternal });
</script>

<style scoped>
.mt-4 {
  margin-top: 1rem;
}

.w-full {
  width: 100%;
}
</style>
